import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:photo_pipeline/photo_pipeline.dart';

/// 提供装配生成的门面，需在 ProviderScope 中覆写。
final pipelineFacadeProvider = Provider<PhotoPipelineFacade>((ref) {
  throw StateError('PhotoPipelineFacade 尚未注入。请在 ProviderScope 中覆写该 Provider。');
});

/// 流水线控制器单例 Provider，供各功能共享使用。
final pipelineControllerProvider = Provider<PhotoPipelineController>((ref) {
  return ref.watch(pipelineFacadeProvider).controller;
});

/// 上传服务 Provider，示例覆盖场景可通过该 Provider 获取实际实现。
final pipelineUploadServiceProvider = Provider<UploadService>((ref) {
  final facade = ref.watch(pipelineFacadeProvider);
  return facade.getService<UploadService>();
});

/// 上传策略流 Provider，供 UI/业务监听当前策略
final pipelineUploadStrategyProvider = StreamProvider<UploadStrategy>((ref) {
  final service = ref.watch(pipelineUploadServiceProvider);
  return service.uploadStrategyStream;
});

/// 初始化流水线服务（仅调用一次，幂等）。
final pipelineInitializationProvider = FutureProvider<void>((ref) async {
  final controller = ref.watch(pipelineControllerProvider);
  await controller.initialize();
  print('[PhotoPipeline] pipelineInitializationProvider success');
});

/// 连接状态流 Provider，直接透传底层 `connectStatusStream`。
final pipelineConnectStatusProvider = StreamProvider<ConnectStatus>((ref) {
  final controller = ref.watch(pipelineControllerProvider);
  return controller.camera.connectStatusStream;
});

/// 当前设备信息流 Provider，便于展示设备名称等。
final pipelineDeviceInfoProvider = StreamProvider<DeviceInfo?>((ref) {
  final controller = ref.watch(pipelineControllerProvider);
  return controller.camera.deviceInfoStream;
});

/// 触发连接的 FutureProvider，可通过 `ref.refresh` 方式手动调用。
/// 
/// 使用自动连接逻辑：
/// - 内部会创建 UsbDetector 并调用 connectWithDetector()
/// - 自动检测已连接的 USB 相机设备
/// - 如果发现设备，会自动请求权限并连接
/// - 如果设备已连接，会立即连接
/// - 如果设备未连接，会等待设备插入后自动连接
final pipelineConnectActionProvider =
    FutureProvider.autoDispose<void>((ref) async {
  print('[PhotoPipeline] 开始自动连接...');
  try {
    final controller = ref.read(pipelineControllerProvider);
    print('[PhotoPipeline] 获取到 PipelineController，开始连接');
    // connect() 内部会使用 connectWithDetector() 自动检测和连接 USB 相机
    await controller.camera.connect();
    print('[PhotoPipeline] 连接完成');
  } catch (e, s) {
    print('[PhotoPipeline] 连接失败: $e\n$s');
    rethrow;
  }
});

/// 断开连接的操作，通常在按钮中通过 `read` 调用即可。
Future<void> disconnectPipeline(WidgetRef ref) async {
  final controller = ref.read(pipelineControllerProvider);
  await controller.camera.disconnect();
}

/// 首屏分页协调器（仅在已连接时提供，否则为 null）
final enhancedFirstPageCoordinatorProvider = Provider.autoDispose<
    ReactivePaginationCoordinator<EnhancedFileInfo, EnhancedQueryParams,
        FileInfo>?>(
  (ref) {
    // 确保完成初始化
    ref.watch(pipelineInitializationProvider);

    final controller = ref.watch(pipelineControllerProvider);
    final connect = ref.watch(pipelineConnectStatusProvider);

    return connect.when(
      data: (status) {
        if (status is Connected) {
          final coordinator =
              controller.camera.createEnhancedPaginationCoordinator(
            initialPagination: const PaginationParams(page: 1, pageSize: 20),
            initialQuery: const EnhancedQueryParams(),
          );
          ref.onDispose(() async {
            await coordinator.dispose();
          });
          return coordinator;
        }
        return null;
      },
      loading: () => null,
      error: (_, __) => null,
    );
  },
);

/// 首屏增强文件信息数据（仅第一页）。复用协调器暴露的流
final enhancedFirstPageProvider =
    StreamProvider.autoDispose<PageData<EnhancedFileInfo>>((ref) {
  final coordinator = ref.watch(enhancedFirstPageCoordinatorProvider);
  if (coordinator == null) {
    return Stream<PageData<EnhancedFileInfo>>.value(
      PageData<EnhancedFileInfo>(
          data: const [], total: 0, page: 1, pageSize: 20),
    );
  }
  return coordinator.stream;
});

/// 上传任务状态筛选（null 表示全部）
final uploadTaskStatusFilterProvider = StateProvider<UploadTaskStatus?>((ref) {
  return null;
});

/// 上传任务分页协调器（依赖连接状态）
final uploadTaskCoordinatorProvider = Provider.autoDispose<
    ReactivePaginationCoordinator<UploadTaskAggregate, UploadTaskQueryParams,
        UploadTaskAggregate>?>(
  (ref) {
    ref.watch(pipelineInitializationProvider);

    final statusFilter = ref.watch(uploadTaskStatusFilterProvider);
    final controller = ref.watch(pipelineControllerProvider);
    final connect = ref.watch(pipelineConnectStatusProvider);

    return connect.when(
      data: (state) {
        if (state is Connected) {
          final coordinator = controller.upload.createTaskPaginationCoordinator(
            initialPagination: const PaginationParams(page: 1, pageSize: 20),
            initialQuery: UploadTaskQueryParams(status: statusFilter),
          );
          ref.onDispose(() async {
            await coordinator.dispose();
          });
          return coordinator;
        }
        return null;
      },
      loading: () => null,
      error: (_, __) => null,
    );
  },
);

/// 上传任务分页数据流
final uploadTaskPageProvider =
    StreamProvider.autoDispose<PageData<UploadTaskAggregate>>((ref) {
  final coordinator = ref.watch(uploadTaskCoordinatorProvider);
  if (coordinator == null) {
    return Stream<PageData<UploadTaskAggregate>>.value(
      PageData<UploadTaskAggregate>(
        data: const [],
        total: 0,
        page: 1,
        pageSize: 20,
      ),
    );
  }
  return coordinator.stream;
});

/// 触发上传任务翻页
void loadMoreUploadTasks(WidgetRef ref) {
  final coordinator = ref.read(uploadTaskCoordinatorProvider);
  coordinator?.nextPage();
}

/// 刷新上传任务分页
void refreshUploadTasks(WidgetRef ref) {
  final coordinator = ref.read(uploadTaskCoordinatorProvider);
  coordinator?.refresh();
}

/// 文件缓存仓库 Provider（T048）
/// 提供 IFileCacheRepository 实例（通过门面提供的工厂方法创建）
final fileCacheRepositoryProvider =
    FutureProvider<IFileCacheRepository>((ref) async {
  // 确保完成初始化
  ref.watch(pipelineInitializationProvider);

  final facade = ref.watch(pipelineFacadeProvider);
  final factory = facade.getService<FileCacheRepositoryFactory>();
  return await factory();
});

/// 文件缓存进度 Provider（T049）
/// 使用 StreamProvider.autoDispose.family 监听指定照片的下载进度
final fileCacheProgressProvider =
    StreamProvider.autoDispose.family<FileCacheProgress?, int>(
  (ref, imageSourceId) async* {
    // 确保完成初始化
    await ref.watch(pipelineInitializationProvider.future);

    // 获取 fileCacheRepository
    final factory = ref
        .watch(pipelineFacadeProvider)
        .getService<FileCacheRepositoryFactory>();
    final fileCacheRepository = await factory();

    // 监听指定照片的下载进度
    yield* fileCacheRepository.watchFileCacheProgress(imageSourceId);
  },
);

/// 文件信息 Provider（T026A）
/// 使用 StreamProvider.autoDispose.family 监听指定文件的信息变化（包括 sourcePath）
/// 使用 Floor 的响应式查询，自动响应数据库变化
final fileInfoProvider = StreamProvider.autoDispose.family<FileInfo?, int>(
  (ref, fileId) async* {
    // 确保完成初始化
    await ref.watch(pipelineInitializationProvider.future);

    // 获取 controller
    final controller = ref.watch(pipelineControllerProvider);

    // 使用 watchFileInfo 订阅文件信息变化（Floor 响应式查询）
    yield* controller.camera.watchFileInfo(fileId);
  },
);

/// 上传策略状态 Provider
final uploadStrategyProvider =
    StreamProvider.autoDispose<UploadStrategy>((ref) {
  final uploadService = ref.watch(pipelineUploadServiceProvider);
  return uploadService.uploadStrategyStream;
});
